package com.example.week11_service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyNewThreadService extends Service {
    public MyNewThreadService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override public int onStartCommand(Intent intent, int flags, final int startId) { Log.d("My NewThreadService", "新任务" + startId + "即将运行"); //为在服务中执行耗时操作，新开一个线程，主 UI 线程就不会出错了 //在运行中，可以重复点击按钮，能开出多个并行执行的耗时任务，它们被有效调试
        new Thread(){ public void run(){ for(int i=0; i<5; i++){ //请到日志中查看启动多个服务后，多项耗时任务的交叉执行
            Log.d("My NewThreadService", "任务" + startId + "正在运行：" + i); try { //下面让线程休眠一定时长的代码代表耗时操作 //可以用实际耗时任务，如下载、计算、播放等代替
                Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } }Log.d("My NewThreadService", "任务" + startId + "运行结束"); } }.start(); //执行完后自行结束 //stopSelf();
        return super.onStartCommand(intent, flags, startId); }@Override public void onDestroy() { super.onDestroy(); }
}